import datetime

# 数据文件路径
DATA_FILE = "personal_finance.txt"

def record_transaction(transaction_type, date, amount, category, note):
    """记录收入或支出"""
    with open(DATA_FILE, "a") as file:
        file.write(f"{transaction_type},{date},{amount},{category},{note}\n")
    print(f"成功记录{transaction_type}：{amount}元，类别：{category}，备注：{note}")

def record_income():
    """记录收入"""
    date = input("请输入日期（格式：YYYY-MM-DD）：")
    amount = float(input("请输入收入金额："))
    if amount <= 0:
        print("收入金额必须为正数！")
        return
    category = input("请输入收入类别（如工资、奖金等）：")
    note = input("请输入备注：")
    record_transaction("收入", date, amount, category, note)

def record_expense():
    """记录支出"""
    date = input("请输入日期（格式：YYYY-MM-DD）：")
    amount = float(input("请输入支出金额："))
    if amount <= 0:
        print("支出金额必须为正数！")
        return
    category = input("请输入支出类别（如餐饮、交通、购物等）：")
    note = input("请输入备注：")
    record_transaction("支出", date, amount, category, note)

def query_records():
    """查询记录"""
    with open(DATA_FILE, "r") as file:
        lines = file.readlines()
        for line in lines:
            print(line.strip())

def view_bills():
    """查看账单"""
    start_date = input("请输入开始日期（格式：YYYY-MM-DD）：")
    end_date = input("请输入结束日期（格式：YYYY-MM-DD）：")
    
    try:
        start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
    except ValueError:
        print("日期格式错误，请使用YYYY-MM-DD格式。")
        return
    
    with open(DATA_FILE, "r") as file:
        lines = file.readlines()
        for line in lines:
            parts = line.strip().split(",")
            date = datetime.datetime.strptime(parts[1], "%Y-%m-%d")
            if start_date <= date <= end_date:
                print(line.strip())

def calculate_statistics():
    """统计功能"""
    total_income = 0
    total_expense = 0
    with open(DATA_FILE, "r") as file:
        lines = file.readlines()
        for line in lines:
            parts = line.strip().split(",")
            transaction_type = parts[0]
            amount = float(parts[2])
            if transaction_type == "收入":
                total_income += amount
            elif transaction_type == "支出":
                total_expense += amount
    net_income = total_income - total_expense
    print(f"总收入：{total_income}元")
    print(f"总支出：{total_expense}元")
    print(f"净收入：{net_income}元")

def main():
    while True:
        print("\n个人账单管理系统")
        print("1. 记录收入")
        print("2. 记录支出")
        print("3. 查询记录")
        print("4. 查看账单")
        print("5. 统计功能")
        print("6. 退出")
        choice = input("请选择功能（输入数字）：")

        if choice == "1":
            record_income()
        elif choice == "2":
            record_expense()
        elif choice == "3":
            query_records()
        elif choice == "4":
            view_bills()
        elif choice == "5":
            calculate_statistics()
        elif choice == "6":
            print("退出系统")
            break
        else:
            print("无效的选择，请重新输入。")

if __name__ == "__main__":
    main()